var ImageFile;
function listenFileSelect() {
    // listen for file selection
    var fileInput = document.getElementById("mypicInput");

    // When a change happens to the File Chooser Input
    fileInput.addEventListener('change', function (e) {
        ImageFile = e.target.files[0]; //Global variable
        var imageurl = URL.createObjectURL(ImageFile);
        console.log(imageurl);
        updateImage(imageurl);
    });
}

function updateImage(imageurl) {
    const image = document.getElementById("mypic-goes-here");
    image.src = imageurl; // Display this image
}

function savePost() {
    // Gather the data from the form
    var calorieData = document.getElementById('calorieInput').value;
    var details = document.getElementById('detailsText').value;
    var image = document.getElementById('mypicInput').files[0];
    

    // Get formatted date
    const now = new Date();
    const dformatted = now.toLocaleString('en-US', {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
    });

    // Create form data object
    var formData = {
        date: dformatted,
        calories: calorieData,
        details: details,
        imageName: image.name
    };

    // Add to post history
    addToPostHistory(formData);
}

function addToPostHistory(data) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
        var users = JSON.parse(localStorage.getItem("users"));
        var email = user["email"];
        const person = users.find(u => u.email === email);

        if (!person.history)
            person.history = [];

        person.history.push(data);
        localStorage.setItem("users", JSON.stringify(users));
        
        addCountLocalStorage(data.calories);
        
        alert('Data saved successfully!');
    } else {
        console.log("No one is logged in");
    }
}

function addCountLocalStorage(value) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    const person = users.find(u => u.email === user["email"]);
    
    if (!person.count) {
        person.count = 0;
    }
    
    person.count = Number(person.count) + Number(value);
    localStorage.setItem("users", JSON.stringify(users));
}

// Initialize file listener
listenFileSelect();